﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using BlockMain_Api;
using BlockMain_Class;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;

namespace BlockMain_Api.Controllers
{
    /// <summary>
    /// 获取链的信息 Json接口
    /// </summary>
    public class GetBlockController : Controller
    {
        //全部DB
        public static MongodbHelpers<PeerList> mon = new MongodbHelpers<PeerList>();

        /// <summary>
        /// 备份链数据
        /// </summary>
        /// <returns></returns>
        public IActionResult PublicBlocksBackupList()
        {
            //开启缓存20秒 todo:需要处理
            HttpContext.Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(20)
            };
            Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
            //正常读取
            var list = mon.QueryAll();
            Publiclist p = new Publiclist();
            p.peernum = list.Count();
            var index = 1;
            List<PeerlistInfo> lp = new List<PeerlistInfo>();

            foreach (var item in list)
            {
                //读取节点列表
                MongodbHelpers<AccountBook> mon = new MongodbHelpers<AccountBook>();//节点账本DB
                var blocklist = mon.QueryAll();
                var height = blocklist.Last().Height;//最后的高度
                var last = blocklist.Last().Hash;//最后的Hash
                var time = blocklist.Last().CreateTime;//最后的时间
                if (index == 1)
                {
                    //获得高度
                    p.height = height;
                    //最新上链
                    var nowup = blocklist.OrderByDescending(a => a.Height).Take(20).Select(a => new AccountBook()
                    {
                        Id = a.Id,
                        Height = a.Height,
                        Hash = a.Hash,
                        Data = a.Data,
                        TimeStamp = a.TimeStamp,
                        PrevHash = a.PrevHash
                    }).ToList();
                    p.BlockchainList = nowup;
                }
                PeerlistInfo pl = new PeerlistInfo();
                pl.No = index;
                pl.Id = item.Id.ToString();
                pl.Name = item.Account;
                pl.state = height == p.height ? 0 : 1;//是否同步
                pl.height = height;
                pl.nowhash = last;
                pl.addtime = time;
                lp.Add(pl);
                index++;

            }
            p.PeerList = lp;
            return Json(p);
        }


        /// <summary>
        /// 获取节点详情 备份链数据
        /// </summary>
        /// <returns></returns>
        public IActionResult BackupPeerInfo(string id)
        {
            //开启缓存20秒 todo:需要处理
            HttpContext.Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(20)
            };
            Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
            try
            {
                MongodbHelpers<AccountBook> mons = new MongodbHelpers<AccountBook>();//节点账本DB
                var peerlist = mon.QueryAll();
                //当前节点
                var nowpeer = peerlist.ToList().FirstOrDefault(a => a.Id.ToString() == id);
                var blocklist = mons.QueryAll().OrderByDescending(a => a.Height).Take(20);
                PeerInfo p = new PeerInfo();
                p.Id = id;
                p.Ip = nowpeer.PeerIp;
                p.state = 0;
                p.addtime = nowpeer.CreateTime;
                p.detail = nowpeer.Detail;
                //hash列表
                p.Blocks = blocklist.Select(a => new BlockItems
                {
                    Heigth = a.Height,
                    Hash = a.Hash,
                    PrevHash = a.PrevHash,
                    addtime = a.CreateTime
                }).ToList();
                return Json(p);
            }
            catch (Exception e)
            {
                return Json(e.Message);
            }
        }

        /// <summary>
        /// 获取Hash详情 备份链数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult BackupBlcokInfo(string hash)
        {
            //开启缓存20秒 todo:需要处理
            HttpContext.Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(20)
            };
            Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
            try
            {
                var peerlist = mon.QueryAll();
                //领袖节点
                var nowpeer = peerlist.First().Id.ToString();
                MongodbHelpers<AccountBook> mons = new MongodbHelpers<AccountBook>();//节点账本DB
                var block = mons.QueryByFirst(a => a.Hash == hash);
                return Json(block);
            }
            catch (Exception e)
            {
                return Json(e.Message);
            }
        }

        /// <summary>
        /// 全部公链节点列表及同步情况  --频发处理-- 存入缓存 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PublicBlocksList()
        {
            //开启缓存20秒 todo:需要处理
            HttpContext.Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(20)
            };
            Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
            //正常读取
            var list = mon.QueryAll();
            Publiclist p = new Publiclist();
            p.peernum = list.Count();
            var index = 1;
            List<PeerlistInfo> lp = new List<PeerlistInfo>();

            foreach (var item in list)
            {
                //读取节点列表
                PeerDB.dbName = "Peer_" + item.Id.ToString(); //当前节点
                PeerMongodbHelpers<AccountBook> mon = new PeerMongodbHelpers<AccountBook>();//节点账本DB
                var blocklist = mon.QueryAll();
                var height = blocklist.Last().Height;//最后的高度
                var last = blocklist.Last().Hash;//最后的Hash
                var time = blocklist.Last().CreateTime;//最后的时间
                if (index == 1)
                {
                    //获得高度
                    p.height = height;
                    //最新上链
                    var nowup = blocklist.OrderByDescending(a => a.Height).Take(20).Select(a => new AccountBook()
                    {
                        Id = a.Id,
                        Height = a.Height,
                        Hash = a.Hash,
                        Data = a.Data,
                        TimeStamp = a.TimeStamp,
                        PrevHash = a.PrevHash
                    }).ToList();
                    p.BlockchainList = nowup;
                }
                PeerlistInfo pl = new PeerlistInfo();
                pl.No = index;
                pl.Id = item.Id.ToString();
                pl.Name = item.Account;
                pl.state = height == p.height ? 0 : 1;//是否同步
                pl.height = height;
                pl.nowhash = last;
                pl.addtime = time;
                lp.Add(pl);
                index++;

            }
            p.PeerList = lp;
            return Json(p);
        }
        /// <summary>
        /// 获取节点详情
        /// </summary>
        /// <returns></returns>
        public IActionResult PeerInfo(string id)
        {
            //开启缓存20秒 todo:需要处理
            HttpContext.Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(20)
            };
            Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
            try
            {
                PeerDB.dbName = "Peer_" + id; //当前节点
                PeerMongodbHelpers<AccountBook> mons = new PeerMongodbHelpers<AccountBook>();//节点账本DB
                var peerlist = mon.QueryAll();
                //当前节点
                var nowpeer = peerlist.ToList().FirstOrDefault(a => a.Id.ToString() == id);
                var blocklist = mons.QueryAll().OrderByDescending(a => a.Height).Take(20);
                PeerInfo p = new PeerInfo();
                p.Id = id;
                p.Ip = nowpeer.PeerIp;
                p.state = 0;
                p.addtime = nowpeer.CreateTime;
                p.detail = nowpeer.Detail;
                //hash列表
                p.Blocks = blocklist.Select(a => new BlockItems
                {
                    Heigth = a.Height,
                    Hash = a.Hash,
                    PrevHash = a.PrevHash,
                    addtime = a.CreateTime
                }).ToList();
                return Json(p);
            }
            catch (Exception e)
            {
                return Json(e.Message);
            }
        }

       /// <summary>
       /// 获取Hash详情
       /// </summary>
       /// <param name="id"></param>
       /// <returns></returns>
        public IActionResult BlcokInfo(string hash)
        {
            //开启缓存20秒 todo:需要处理
            HttpContext.Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(20)
            };
            Response.Headers[HeaderNames.Vary] = new string[] { "Accept-Encoding" };
            try
            {
                var peerlist = mon.QueryAll();
                //领袖节点
                var nowpeer = peerlist.First().Id.ToString();
                PeerDB.dbName = "Peer_" + nowpeer; //当前节点
                PeerMongodbHelpers<AccountBook> mons = new PeerMongodbHelpers<AccountBook>();//节点账本DB
                var block=mons.QueryByFirst(a=>a.Hash==hash);
                return Json(block);
            }
            catch (Exception e)
            {
                return Json(e.Message);
            }
        }
    }
}